// Thud - a dynamic object-oriented language
// Copyright (C) 2009,2010 David H. Hovemeyer <david.hovemeyer@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

/*
 * DataInputStream.cpp
 *
 *  Created on: Nov 28, 2009
 *      Author: dhovemey
 */

#include <memory>
#include <netinet/in.h>
#include "util/String.h"
#include "util/EOFException.h"
#include "util/Utf8TextCoder.h"
#include "util/DataInputStream.h"

DataInputStream::DataInputStream(InputStream *inputStreamToAdopt)
	: m_delegate(inputStreamToAdopt)
{

}

DataInputStream::~DataInputStream()
{
	delete m_delegate;
}

int DataInputStream::read()
{
	return m_delegate->read();
}

size_t DataInputStream::read(void *buf, size_t n)
{
	return m_delegate->read(buf, n);
}

bool DataInputStream::atEOF()
{
	return m_delegate->atEOF();
}

uint8_t DataInputStream::readByte()
{
	uint8_t buf;
	m_delegate->readFully((void *) &buf, 1);
	return buf;
}

uint16_t DataInputStream::readShort()
{
	uint16_t buf;
	m_delegate->readFully((void *) &buf, sizeof(buf));
	return ntohs(buf);
}

uint32_t DataInputStream::readInt()
{
	uint32_t buf;
	m_delegate->readFully((void *) &buf, sizeof(buf));
	return ntohl(buf);
}

std::wstring DataInputStream::readString()
{
	std::auto_ptr<Utf8TextCoder> coder(new Utf8TextCoder());

	uint16_t len = readShort();
	std::wstring ws;
	for (size_t i = 0; i < len; i++) {
		long c = coder->decode(m_delegate);
		if (c < 0) {
			throw EOFException(L"Unexpected EOF reading UTF-8 string", i);
		}
		ws += wchar_t(c);
	}
	return ws;
}
